<?php
/**
 * Created by PhpStorm.
 * User: xuaq
 * Date: 2019/2/27
 * Time: 16:07
 */

namespace App\Modules\Rtdata\Repositories;

use App\Modules\Rtdata\Constant\RtdataConstant;
use App\Modules\Rtdata\Process\BuyOrderProcess;
use Illuminate\Support\Facades\Redis;
use Closure;

class OrderPubSubRepository
{
    protected $redis;

    protected $connection_name='rtdata_orders';

    public function __construct()
    {
        $this->redis = Redis::connection($this->connection_name);
    }

    public function buyOrderPublish(array $buy_order)
    {
        return $this->redis->publish(RtdataConstant::BUY_CHANNEL_NAME, self::jsonEncode($buy_order));
    }

    public function subscribeBuyOrder(BuyOrderProcess $buyOrderProcess)
    {
        $closure = self::makeClosure($buyOrderProcess, 'buyOrdersProcess');
        $this->redis->subscribe(RtdataConstant::BUY_CHANNEL_NAME, $closure);
    }

    protected static function jsonEncode(array $array)
    {
        return json_encode($array);
    }

    protected static function makeClosure($obj, $method)
    {
        return Closure::fromCallable([$obj, $method]);
    }
}